const express = require("express");
const next = require("next");
const fs = require("fs");
const url = require("url");
const UUID = require("uuidjs");
const bodyParser = require("body-parser");
const dev = process.env.NODE_ENV !== "production";

const app = next({ dev });

const handler = app.getRequestHandler();

app.prepare().then(() => {
  const server = express();
  // parse application/x-www-form-urlencoded
  server.use(bodyParser.urlencoded({ extended: false }));

  // parse application/json
  server.use(bodyParser.json());

  server.get("/hello", (req, res) => {
    res.send("Hello Next.js");
  });
  server.get("/getRecords", (req, res) => {
    try {
      let records = fs.readFileSync(require.resolve("./record.json"), "utf8");
      console.log(records);
      records = records.toString();
      records = JSON.parse(records);
      // 前端axios可以自动解析成json
      res.send(records);
    } catch (e) {
      console.log(e);
      res.send("error");
    }
  });
  server.post("/addRecords", (req, res) => {
    const body = req.body;
    console.log(body);
    let records = fs.readFileSync(require.resolve("./record.json"), "utf8");
    console.log(records);
    records = records.toString();
    records = JSON.parse(records);
    let obj = {};
    obj.id = UUID.generate();
    obj.title = body.name;
    obj.url = body.url;
    records.push(obj);
    fs.writeFileSync(
      require.resolve("./record.json"),
      JSON.stringify(records),
      "utf8"
    );
    res.send(records);
  });

  server.post("/deleteItem", (req, res) => {
    const id = req.body.id;
    let records = fs.readFileSync(require.resolve("./record.json"), "utf8");
    console.log(records);
    records = records.toString();
    records = JSON.parse(records);
    records = records.filter((ele) => ele.id !== id);
    fs.writeFileSync(
      require.resolve("./record.json"),
      JSON.stringify(records),
      "utf8"
    );
    res.send(records);
  });
  server.get("*", (req, res) => {
    handler(req, res);
  });
  server.listen(3000, () => console.log("服务器启动成功"));
});
